//
//  DataRequest.m
//  MMairs
//
//  Created by dongguozheng on 2017/2/22.
//  Copyright © 2017年 dongguozheng. All rights reserved.
//

#import "DataRequest.h"
#import "SessionManager.h"
@implementation DataRequest
+(instancetype)shareAFNetWorking
{
    static DataRequest *netData=nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        netData=[[DataRequest alloc]init];
    });
    return netData;
}

//判断当前是否有网络链接
+(BOOL)animalNetWorkConnection{
    
    Reachability * reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    BOOL animalConnection;
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            animalConnection = NO;
            break;
            
        case ReachableViaWiFi:
            animalConnection = YES;
            break;
            
            
        case ReachableViaWWAN:
            animalConnection = YES;
            break;
            
        default:
            break;
    }
    
    
    return animalConnection;
}


//配置
- (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"wtqssl" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    //    securityPolicy.pinnedCertificates =@[certData];
    securityPolicy.pinnedCertificates =[NSSet setWithObjects:certData, nil];
    return securityPolicy;
}

//配置HTTPS

//文件上传，
-(void)UploadImageWithPOST:(NSString *)POST WithParameters:(NSDictionary *)dic withAuthorization:(NSString *)authorization WithUploadImage:(UIImage *)image successBlock:(SuccessBlock)success FailBlock:(failBlock)fail
{
    [SessionManager sharedSessionManager].manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    //接收类型不一致请替换一致text/html或别的
    [[SessionManager sharedSessionManager].manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
    [SessionManager sharedSessionManager].manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    // 加上这行代码，https ssl 验证。
    [[SessionManager sharedSessionManager].manager setSecurityPolicy:[self customSecurityPolicy]];
    [[SessionManager sharedSessionManager].manager POST:POST parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        NSData *imageData =UIImageJPEGRepresentation(image,1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];

}

//get请求
-(void)GETRequestWithUrl:(NSString *)urlString paramaters:(NSDictionary *)paramaters WithAuthorization:(NSString *)authorization successBlock:(SuccessBlock)success FailBlock:(failBlock)fail
{
    
    [SessionManager sharedSessionManager].manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    [[SessionManager sharedSessionManager].manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
    // 加上这行代码，https ssl 验证。
    [[SessionManager sharedSessionManager].manager setSecurityPolicy:[self customSecurityPolicy]];
    [[SessionManager sharedSessionManager].manager GET:urlString parameters:paramaters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];

}

//post请求
-(void)POSTRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters WithAuthorization:(NSString *)authorization successBlock:(SuccessBlock)success FailBlock:(failBlock)fail
{
    [SessionManager sharedSessionManager].manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    [[SessionManager sharedSessionManager].manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
    // 加上这行代码，https ssl 验证。
    [[SessionManager sharedSessionManager].manager setSecurityPolicy:[self customSecurityPolicy]];
    [[SessionManager sharedSessionManager].manager POST:urlString parameters:paramaters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}
@end
